<?php
/*
 * IWA assignment 2 - service.php 
 * Maximilian Einoeder
 * Mark Mensing
 */

//include phpSesame Framework
require_once "phpSesame.php";
require_once "arc2/ARC2.php";

// Eventful API configuration parameters
$app_key='58SW64N5rgq2VXQ7';
$keywords='test';
$domain = 'http://api.eventful.com';
$service = '/rest/events/search';

//define RDF store
$sesame = array('url' => 'http://localhost:8080/openrdf-sesame', 'repository' => 'ass2');
$store = new phpSesame($sesame['url'], $sesame['repository']);


//Get the input text
$query = $_POST['textQuery'];

$keywords = array();

//Release a regex on the input, to retrieve the literals
preg_match_all('/"([^"]+)"/', $query, $keywords);


//For now print out the keywords
$count = count($keywords[0]);

$key = $keywords[1][0];
for($i = 1; $i < $count; $i++) {
    $key.='+'.$keywords[1][$i];
}

try {
    // create API call 
    $url = $domain.$service.'?app_key='.$app_key.'&keywords='.$key;
    $url = str_replace(" ","+",$url);

    // output URL
    echo "<h2>Called URL:</h2> ".$url;

    // get return from Service
    $result=file_get_contents($url);

    // parse XML
    $xmlresult = new SimpleXMLElement($result);
} catch (Exception $e) {
    echo "</br><b>Error:</b> There was a problem with accessing the eventful API. </br></br>";
}


try {
	// define rdf context
	$context = "http://www.iwa.com/assignment2/";
	
	// parse xml file and create per entry...
	foreach($xmlresult->events->children() as $x) {
	
	// multiple triples for RDF store
	$index = array($context.$x['id'] => array(
	    "rdf:ch_type" => array("lode:Event"),
	    "lode:atPlace" => array($x->venue_name),
	    "lode:atPlace" => array($x->city_name),
	    "lode:illustrate" => array($x->url),
	    "rdfs:label" => array($x->title),
	    "rdfs:comment" => array($x->description),
	    "lode:inSpace" => array($context.$x['id']."space")
	),
	$context.$x['id']."space" => array(
	    "rdf:ch_type" => array("geo:SpatialThing"),
	    "geo:latitude" => array($x->latitude),
	    "geo:longitutde" => array($x->longitude)
	)
	);
	
	// configure namespaces
	$conf = array('ns' => array('rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'owl' => 'http://www.w3.org/2002/07/owl#','lode' => 'http://linkedevents.org/ontology/', 'geo' => 'http://www.w3.org/2003/01/geo/wgs84_pos#', 'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#'));
	$serializer = ARC2::getRDFXMLSerializer($conf);
	
	// store triples in RDF store
	$rdfxml = $serializer->getSerializedIndex($index);
	$inputFormat = phpSesame::RDFXML; // Optional - defaults to RDFXML
	$store->append($rdfxml, $context, $inputFormat);
}
} catch(Exception $e) {
	echo "</br><b>Error:</b> There was a problem with inserting the data into the tripple store. </br></br>";
}


try {
	// catch query from GET (htmlentities because of <, > etc.)
	$query = htmlentities($query);
	
	//print query
	echo "<br /><h2>Your Query:</h2>".$query;
	
	// apply SPARQL query on RDF store
	$resultFormat = phpSesame::SPARQL_XML; // The expected return type, will return a phpSesame_SparqlRes object (Optional)
	$lang = "sparql"; // Can also choose SeRQL (Optional)
	$infer = true; // Can also choose to explicitly disallow inference. (Optional)
	
	// html_entitty_decode in order to bring &lt; to <  etc.
	$result = $store->query(html_entity_decode($query), $resultFormat, $lang, $infer);
	
	// Print result
	echo "<br /><h2>Your result:</h2><table border=\"1\">";
	
	// parse result and print it as a nice table with even nicer table head
	if($result->hasRows())
	{
		echo "<tr>";
		foreach(end($result->getRows()) as $key => $entry) {
			if(substr($key,-5)!="_type") echo "<th>".$key."</th>";
		}
		echo "</tr>";	
		foreach($result->getRows() as $row)
		{
			$count = sizeof($row)/2;
			echo "<tr>";
			foreach($row as $x) {
				if($x!="uri" && $x!="literal") echo "<td>".$x."</td>";
			}
			echo "</tr>";
		}
	}
} catch (Exception $e) {
	echo "</br><b>Error:</b> There was a problem processing your query. Please check if your query is correct. </br></br>";
}


?>